﻿#region Copyright Notice
// 
// 
//  
//  Copyright (c) 2009-2011 Anindya Chatterjee
//  
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//  
//      http://www.apache.org/licenses/LICENSE-2.0
//  
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// 
// 
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace AbstractClass.Extensions
{
    /// <summary>
    /// Contains extension methods for <see cref = "Type"/>.
    /// </summary>
    public static class TypeExtensions
    {
        /// <summary>
        /// Determines whether a type is castable to another type.
        /// </summary>
        /// <param name="from">The type to cast.</param>
        /// <param name="to">The final type to cast into.</param>
        /// <returns>
        /// 	<c>true</c> if the type is castable; otherwise, <c>false</c>.
        /// </returns>
        public static bool IsCastableTo(this Type from, Type to)
        {
            if (to.IsAssignableFrom(from))
            {
                return true;
            }

            IEnumerable<MethodInfo> methods = from.GetMethods(BindingFlags.Public | BindingFlags.Static)
                .Where(
                    m => m.ReturnType == to &&
                         (m.Name == "op_Implicit" ||
                          m.Name == "op_Explicit")
                );

            if (methods.Count() == 0)
            {
                methods = to.GetMethods(BindingFlags.Public | BindingFlags.Static)
                    .Where(
                        m => m.ReturnType == to &&
                             m.GetParameters().Length > 0 &&
                             m.GetParameters()[0].ParameterType == from &&
                             (m.Name == "op_Implicit" ||
                              m.Name == "op_Explicit")
                    );
                return methods.Count() > 0;
            }
            return true;
        }
    }
}